"""
认证 API 路由定义 (routes/auth_routes.py)

使用 Flask Blueprint 组织用户身份验证相关的 API 端点。
"""
from flask import Blueprint, jsonify, request, g
from models.user import (
    authenticate_user, get_user_by_id, change_password as user_change_password,
    create_user
)
from utils.auth_utils import decode_token, auth_required
import logging

# 配置日志记录器
logger = logging.getLogger(__name__)

# 认证 API 蓝图
auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/auth/login', methods=['POST'])
def login():
    """API 端点：用户登录"""
    if not request.json:
        return jsonify({"error": "无效请求，需要 JSON 数据"}), 400
    
    username = request.json.get('username', '')
    password = request.json.get('password', '')
    
    if not username or not password:
        return jsonify({"error": "用户名和密码必填"}), 400
    
    # 验证用户凭据
    auth_result = authenticate_user(username, password)
    if not auth_result:
        logger.warning(f"登录失败: {username}")
        return jsonify({"error": "用户名或密码错误"}), 401
    
    logger.info(f"用户登录成功: {username}")
    return jsonify(auth_result), 200

@auth_bp.route('/auth/user', methods=['GET'])
@auth_required
def get_current_user():
    """API 端点：获取当前登录用户信息"""
    # auth_required 装饰器已经将解码的用户 ID 放入 g.user_id
    user = get_user_by_id(g.user_id)
    if not user:
        return jsonify({"error": "未找到用户"}), 404
    
    return jsonify(user), 200

@auth_bp.route('/auth/change-password', methods=['POST'])
@auth_required
def change_password_route():
    """API 端点：更改密码"""
    if not request.json:
        return jsonify({"error": "无效请求，需要 JSON 数据"}), 400
    
    old_password = request.json.get('oldPassword', '')
    new_password = request.json.get('newPassword', '')
    
    if not old_password or not new_password:
        return jsonify({"error": "旧密码和新密码必填"}), 400
    
    # 验证并更改密码
    success = user_change_password(g.user_id, old_password, new_password)
    if not success:
        return jsonify({"error": "旧密码不正确"}), 400
    
    logger.info(f"用户 {g.user_id} 密码更改成功")
    return jsonify({"message": "密码更改成功"}), 200

@auth_bp.route('/auth/register', methods=['POST'])
def register():
    """API 端点：注册新用户"""
    if not request.json:
        return jsonify({"error": "无效请求，需要 JSON 数据"}), 400
    
    username = request.json.get('username', '')
    password = request.json.get('password', '')
    email = request.json.get('email', '')
    
    if not username or not password:
        return jsonify({"error": "用户名和密码必填"}), 400
    
    # 创建新用户
    new_user = create_user(username, password, email)
    if not new_user:
        return jsonify({"error": "用户名已存在"}), 409
    
    logger.info(f"新用户注册成功: {username}")
    
    # 自动登录新用户
    auth_result = authenticate_user(username, password)
    return jsonify(auth_result), 201 